import React, { Fragment } from 'react';
import './todoList.css'
import TodoItem from './TodoItem'

class TodoList extends React.Component {
    // constructor在组建创建的第一时刻自动被执行
    constructor(props) {
        super(props);
        // 提高性能
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleKeyup = this.handleKeyup.bind(this);
        this.handleItemClick = this.handleItemClick.bind(this);
        // 在组建中创建了2个数据，数据一定要定义在state中
        this.state = {
            inputValue: '',
            list: []
        }
    }
    handleInputChange(e) {
        // 改变组件中的数据
        this.setState({
            inputValue: e.target.value
        })
    }
    handleKeyup(e) {
        if (e.keyCode === 13 && e.target.value !== '') {
            let list = [...this.state.list, this.state.inputValue]
            this.setState({
                list,
                inputValue: ''
            })
        }
    }
    handleItemClick(index) {
        let list = [...this.state.list]
        list.splice(index, 1) //删除该下标对应的值
        this.setState({
            list
        })
    }
    getListItems() {
        // 父子组件的概念
        // 父组件通过属性的形式向子组件传值
        return this.state.list.map((value, index) => {
            return (
            <TodoItem 
                content={value} 
                index={index} 
                key={index} 
                deleteFunction={this.handleItemClick}
            />)
        })
    }
    render() {
        console.log('render')
        return (
            <Fragment>
                <h1>TodoList</h1>
                {/* jsx的标准注释写法*/}
                <label htmlFor="myInput">请输入内容：</label>
                <input
                    id="myInput"
                    className="input"
                    value={this.state.inputValue}
                    onChange={this.handleInputChange} // 绑定this
                    onKeyUp={this.handleKeyup}
                />
                <ul>
                    {this.getListItems()}
                </ul>
            </Fragment>
        )
    }
}
export default TodoList;